##########################################################################################

library(data.table)
library(optparse)
library(parallel)
library(dplyr)

##########################################################################################

option_list <- list(
    make_option(c("--sample_list_file"), type = "character"),
    make_option(c("--rsem_file"), type = "character"),
    make_option(c("--out_file"), type = "character"),
    make_option(c("--gtf_file"), type = "character")
)

if(1!=1){
    
    sample_list_file <- "~/20220915_gastric_multiple/rna_batch1/analysis/config/tumor_normal.list"
    rsem_file <- "~/20220915_gastric_multiple/rna_batch1/analysis/RSEM/CombineTPM.tsv"
    out_file <- "~/20220915_gastric_multiple/rna_batch1/analysis/RSEM/CombineTpm.FilterLowExpression-MergeMutiSample.tsv"
    gtf_file <- "~/ref/GTF/gencode.v19.ensg_genename.txt"

}

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

sample_list_file <- opt$sample_list_file
rsem_file <- opt$rsem_file
gtf_file <- opt$gtf_file
out_file <- opt$out_file

##########################################################################################

info <- data.frame(fread(sample_list_file))
dat_tpm <- data.frame(fread(rsem_file))
colnames(dat_tpm) <- gsub( "X" , "" , colnames(dat_tpm))
dat_gtf <- data.frame(fread(gtf_file , header = F))
colnames(dat_gtf) <- c("gene_id" , "Hugo_Symbol")

##########################################################################################

class_type <- c( "Normal" , "IM" , "IGC" , "DGC")

igc_class <- c("IM + IGC + DGC" , "IM + IGC")
dgc_class <- c("IM + IGC + DGC" , "IM + DGC")

im_igc_sample <- unique(info[info$Type %in% igc_class , "ID"])
im_dgc_sample <- unique(info[info$Type %in% dgc_class , "ID"])

##########################################################################################
## 俺人的不同病理类型合并样本
## 若一个人同一病理类型多个样本，均中位数

dat_tpm_all <- Reduce(function(x,y)merge( x , y , by = "gene_id"),mclapply(unique(info$ID) , function(id){

    tmp_info <- subset( info , ID == id )

    result <- data.frame()
    ## 若一个人同一病理类型多个样本，均中位数
    for(class in unique(tmp_info$Class)){
        tmp_sample <- tmp_info[tmp_info$Class==class,"Tumor"]
        tmp_tpm <- dat_tpm[,c("gene_id" , tmp_sample)]

        if(ncol(tmp_tpm) > 2){
            value <- apply( tmp_tpm[,-1] , 1 , median )
        }else{
            value <- tmp_tpm[,-1]
        }
        
        result_tmp <- data.frame( gene_id = tmp_tpm$gene_id , sample = value )
        colnames(result_tmp)[2] <- paste0( id , "_" , class)

        if( nrow(result) > 0){
            result <- merge(result , result_tmp)
        }else{
            result <- result_tmp
        }
    }

    ## Normal样本
    tmp_sample <- tmp_info[tmp_info$Class==class,"Normal"]
    if(tmp_sample!="#N/A"){
        tmp_tpm <- dat_tpm[,c("gene_id" , tmp_sample)]
        value <- tmp_tpm[,-1]
        result_tmp <- data.frame( gene_id = tmp_tpm$gene_id , sample = value )
        colnames(result_tmp)[2] <- paste0( id , "_" , "Normal")

        ## 输出结果
        result <- merge(result , result_tmp)
    }
    
    result

},mc.cores=10))

## 只关注Normal、IM、IGC、DGC的表达情况
col_names <- grep( paste( c( "gene_id" , class_type) , collapse="|") , colnames(dat_tpm_all) , value = T )
dat_tpm_all <- dat_tpm_all[,col_names]

##########################################################################################
## 只取存在IM+IGC或IM+DGC的样本
use_sample <- paste0(unique(c(im_igc_sample , im_dgc_sample)) , collapse = "|")
use_col <- c( "gene_id" , grep( use_sample , colnames(dat_tpm_all) , value = T ))
dat_tpm_all <- dat_tpm_all[,use_col]

##########################################################################################
## 过滤中位TPM小于1的基因
record_exp <- apply( dat_tpm_all[,-1] , 1 , median ) > 1
dat_tpm_all <- dat_tpm_all[which(record_exp),]

dat_tpm_all$gene_id <- sapply( strsplit(dat_tpm_all$gene_id , "[.]") , "[" , 1 )
dat_tpm_all_out <- merge( dat_gtf , dat_tpm_all)
dat_tpm_all_out <- dat_tpm_all_out[!duplicated(dat_tpm_all_out$Hugo_Symbol),]

write.table( dat_tpm_all_out , out_file , row.names = F , sep = "\t" , quote = F)


##########################################################################################
